#coding=utf-8

import codecs
import urllib
import re
from BeautifulSoup import BeautifulSoup
import sys
reload(sys)
sys.setdefaultencoding('utf8')

class ctAnalytics():
	def __init__(self,setting={}):
		self.setting = setting
		self.class_n_hash = ["1,2","3,4","5,6","7,8","9,10","11,12"]
	'''
	分析课表
	'''
	def table_do(self,ct_html):
		soup = BeautifulSoup(ct_html, fromEncoding='utf-8')
		Table1 = soup.find("table", {"id": "Table1"}) #课表
		Table2 = soup.find("table", {"id": "Table2"}) #学生及课表相关信息
		Table3 = soup.find("table", {"id": "Table3"}) #其他课程信息
		'''
		寻找 学生及课表相关信息
		'''
		xn  = Table2.find("select", {"name": "xnd"}).find("option", {"selected": "selected"}).string
		xq  = Table2.find("select", {"name": "xqd"}).find("option", {"selected": "selected"}).string

		ct_info = {'xn':xn,'xq':xq}
		'''
		寻找 课表信息
		'''
		Table1_tr = Table1.findAll("tr")
		ct_data = [] #定义课表字典
		row = 0
		for tr in Table1_tr: #循环课表每一行
			if row>1 and row%2==0: #只需要课表所在行（除0行以外的偶数行）
				y = row/2
				col = 0
				for td in tr.findAll("td"): #循环课表一行中的每一列
					x = 0
					if y%2==1 and col>1: #只需课表所在列（奇数行从第3列开始，偶数行从第二列开始）
						x = col-1
					if y%2==0 and col>0:
						x = col
					if x != 0:
						items     = td.contents
						items_str = ""
						for item in items:
							items_str += str(item)
						for class_item in items_str.split("<br /><br />"):
							class_item_arr = self.table_tdAnalytics(y,x,class_item)
							if len(class_item_arr) > 0: 
								ct_data.append(class_item_arr) #存储课表信息
					col += 1
			row += 1
		'''
		分析 table3
		'''
		ct_more = {}
		
		return {"ct_info":ct_info,"ct_data":ct_data,"ct_more":ct_more}
	'''
	分析课表html中td的内容
	'''
	def table_tdAnalytics(self,class_n,week_d,class_item):
		item_dict = {}
		item_item_list = class_item.split("<br />")
		item_item_list_len = len(item_item_list)

		if item_item_list_len != 0 and self.setting["name"] == "guoren":
			item_item_list_temp = {}
			for i in xrange(0,item_item_list_len):
				if i==0:
					item_item_list_temp[0] = item_item_list[0]
					item_item_list_temp[1] = ""
				else:
					item_item_list_temp[i+1] = item_item_list[i]
			item_item_list = item_item_list_temp
			item_item_list_len = len(item_item_list)

		if not item_item_list_len in [4,5,6,7]:
			return {}

		item_dict["title"] = item_item_list[0]
		item_dict["type"]  = item_item_list[1]

		item_item_list_1 = re.split('{第|-|周}|周\||\n',item_item_list[2])
		item_dict["week_s"] = item_item_list_1[1]
		item_dict["week_e"] = item_item_list_1[2]

		item_dict["week_d"]  = str(week_d)
		item_dict["class_n"] = self.class_n_hash[class_n-1]

		item_dict["teacher"] = item_item_list[3]
		if item_item_list_len in [5,7]:
			item_dict["address"] = item_item_list[4]
		else:
			item_dict["address"] = ""

		return item_dict

	def info_do(self,ct_html):
		soup = BeautifulSoup(ct_html, fromEncoding='utf-8')
		Table1 = soup.find("table") #
		'''
		寻找 个人信息
		'''
		Table1_tr = Table1.findAll("tr")
		ct_title = []
		ct_data  = []
		
		for tr in Table1_tr: #循环每一行
			col         = 1
			for td in tr.findAll("td"): #循环每一列
				if col < 7:
					span_str = ""
					span  = td.findAll("span")
					if len(span) != 0:
						span_str = span[0].string

					input = td.findAll("input")
					if len(input) != 0:
						try:
							span_str = input[0]["value"]
						except KeyError:
							span_str = ""

					select = td.findAll("select")
					if len(select) != 0:
						option = select[0].findAll("option",attrs={'selected':''})
						if(len(option) != 0):
							span_str = option[0].string
						else:
							span_str = select[0].findAll("option")[0].string

					if span_str == None:
						span_str = ""

					if col%2 == 0 and is_data:
						ct_data.append(span_str)
					else:
						if span_str != "":
							is_data = True
							ct_title.append(span_str)
						else:
							is_data = False
					col += 1

		return {'title':ct_title,'data':ct_data}

	def exam_do(self,ct_html):
		soup = BeautifulSoup(ct_html, fromEncoding='utf-8')
		Table1 = soup.find("table", {"id": "DataGrid1"}) #成绩
		'''
		寻找 考试信息
		'''
		Table1_tr = Table1.findAll("tr")
		ct_title = []
		ct_data  = []
		row      = 0
		for tr in Table1_tr: #循环每一行
			ct_row_data = []
			for td in tr.findAll("td"): #循环每一列
				if td.string == None:
					td.string = ""
				ct_row_data.append(td.string.strip("&nbsp;")) #存储信息

			if row == 0:
				ct_title = ct_row_data
			else:
				ct_data.append(ct_row_data)
			row += 1
		return {'title':ct_title,'data':ct_data}

	def score_do(self,ct_html):
		soup = BeautifulSoup(ct_html, fromEncoding='utf-8')
		Table1 = soup.find("table", {"id": "Datagrid1"}) #成绩
		'''
		寻找 成绩信息
		'''
		Table1_tr = Table1.findAll("tr")
		ct_title = []
		ct_data  = []
		row      = 0
		for tr in Table1_tr: #循环每一行
			ct_row_data = []
			for td in tr.findAll("td"): #循环每一列
				a = td.findAll("a")
				if len(a) == 1:
					td.string = a[0].string
				if td.string == None:
					td.string = ""
				ct_row_data.append(td.string.strip("&nbsp;")) #存储信息

			if row == 0:
				ct_title = ct_row_data
			else:
				ct_data.append(ct_row_data)
			row += 1
		return {'title':ct_title,'data':ct_data}